package com.etooling.framework.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.etooling.framework.entity.DataDir;
import com.etooling.framework.entity.Org;
import com.etooling.framework.repository.DataDirRepository;
import com.etooling.framework.repository.OrgRepository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QywxUtil {
    private static Map<String, QywxUtil> qywxUtilMap = new HashMap<>();


    public String getAgentId() {
        return agentId;
    }


    //应用ID
    private String agentId = "";

    private void setCorpId(String corpId) {
        this.corpId = corpId;
    }

    //企业应用ID
    private String corpId = "";
    //内部应用唯一秘钥
    private String innersecret = "";

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    //qywxAccessToken
    private String token = "";

    private Date lastTokenTime;
    private String companyId;

    private Date getLastTokenTime() {
        return lastTokenTime;
    }

    private void setLastTokenTime(Date lastTokenTime) {
        this.lastTokenTime = lastTokenTime;
    }

    public void setAgentId(String agentId) {
        this.agentId = agentId;
    }

    public String getCorpId() {
        return corpId;
    }

    public String getInnersecret() {
        return innersecret;
    }

    private static Map<String, QywxUtil> getQywxUtilMap() {
        return qywxUtilMap;
    }

    private String getCompanyId() {
        return companyId;
    }

    private void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    private QywxUtil() {

    }

    public static QywxUtil getInstance(String companyId) {

        if (qywxUtilMap.get(companyId) != null) {
            QywxUtil instance = qywxUtilMap.get(companyId);
            Date lastTime = instance.getLastTokenTime();
            //正常一个token的时间是两小时
            Double minutes = DateFm.get_xc_minute(lastTime, new Date());
            if (minutes > 100) {
                //重新获取token
                JSONObject token_ = instance.getQywxAccessToken();
                String tokenStr = token_.getString("access_token");
                instance.setLastTokenTime(new Date());
                instance.setToken(tokenStr);
                instance.setCompanyId(companyId);
                qywxUtilMap.put(companyId, instance);
            }
            return instance;
        } else {
            //去数据库拿配置
            DataDirRepository dataDirRepository = (DataDirRepository) SpringContextUtil.getBean("dataDirRepository");
            List<DataDir> dataDirList = dataDirRepository.getByCompanyId(companyId, "企业微信配置");
            String corpId_ = "";
            String agentId_ = "";
            String secret_ = "";
            for (DataDir d : dataDirList) {
                if ("corpId".equals(d.getDisplayValue())) {
                    corpId_ = d.getDirValue();
                }
                if ("agentId".equals(d.getDisplayValue())) {
                    agentId_ = d.getDirValue();
                }
                if ("secret".equals(d.getDisplayValue())) {
                    secret_ = d.getDirValue();
                }
            }
            if (WebUtils.checkStr(corpId_) && WebUtils.checkStr(agentId_) && WebUtils.checkStr(secret_)) {
                QywxUtil instance = new QywxUtil(agentId_, corpId_, secret_);
                //获取token
                JSONObject token_ = instance.getQywxAccessToken();
                String tokenStr = token_.getString("access_token");
                instance.setToken(tokenStr);
                instance.setLastTokenTime(new Date());
                instance.setCompanyId(companyId);
                instance.setCorpId(corpId_);
                instance.setAgentId(agentId_);
                qywxUtilMap.put(companyId, instance);
                return instance;
            } else {
                return null;
            }


        }
    }

    private QywxUtil(String agentId, String corpId, String innersecret) {
        this.agentId = agentId;
        this.corpId = corpId;
        this.innersecret = innersecret;
    }


    // 获取企业微信accessToken
    private JSONObject getQywxAccessToken() {
        System.out.println("获取accessToken");
        //这个url链接地址和参数皆不能变
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + innersecret;
        JSONObject jsonObject = new JSONObject();

        try {
            String message = HttpClient.get(url);
            jsonObject = JSONObject.parseObject(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    /**
     * 同步部门信息
     *
     * @return {@link String}
     */
    private void syncDepartmentInfo() throws Exception {
        String ticket = null;
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=" + this.getToken();
        try {

            String orgInfoStr = HttpClient.get(url);
            JSONObject json = JSONObject.parseObject(orgInfoStr);
            if (json.getString("errmsg").equals("ok")) {
                OrgRepository orgRepository = (OrgRepository) SpringContextUtil.getBean("orgRepository");
                JSONArray jsonArray = json.getJSONArray("department_id");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Integer orgId = jsonObject.getInteger("id");
                    //同步部门信息
                    Org org = orgRepository.getByAuthId(orgId);
                    if (org == null) {
                        //获取明细信息
                        String orgDetailUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/get?access_token=" + this.getToken() + "&id=" + orgId;
                        String orgDetailJson = HttpClient.get(orgDetailUrl);
                        JSONObject jsonOrg = JSONObject.parseObject(orgDetailJson);
                        if (jsonOrg.getString("errmsg").equals("ok")) {
                            org = new Org();
                            org.setCompanyId(this.getCompanyId());
                            String name = jsonOrg.getString("name");
                            String name_en = jsonOrg.getString("name_en");
                            Integer parentid = jsonOrg.getInteger("parentid");
                            Org parentOrg = orgRepository.getByAuthId(parentid);
                            Integer order = jsonOrg.getInteger("order");
                            if (parentOrg != null) {
                                org.setParentId(parentOrg.getParentId());
                            }
                            org.setName(name);
                            org.setStatus(Org.SYNC_NEW);
                            orgRepository.save(org);
                        }
                    }

                    //同步员工信息
//                    Org org = orgRepository.getByAuthId(orgId);
                }
            } else {
                throw new Exception(json.getString("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param code 通过 授权链接  获取的 客户Code
     * @return
     */
    public JSONObject getQywxUserInfo(String code) {
        JSONObject jsonObject = new JSONObject();
        String oauthUserUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + this.getToken() + "&code=" + code;
        System.out.println("获取用户信息的访问的地址");
        System.out.println(oauthUserUrl);
        try {
            String message = HttpClient.get(oauthUserUrl);
            jsonObject = JSONObject.parseObject(message);
            if (jsonObject.getString("errmsg").equals("ok")) {
                //拿用户的详细信息
                String userTicket = jsonObject.getString("user_ticket");
                JSONObject ticket = new JSONObject();
                ticket.put("user_ticket", userTicket);
                String userInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token=" + this.getToken() + "&user_ticket=" + userTicket;
                String userInfoJson = HttpClient.sendPost(userInfoUrl, ticket);
                jsonObject = JSONObject.parseObject(userInfoJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 批量获取客户详情
     *
     * @param userId
     * @return
     */
    public JSONObject getClientListByUserId(String userId) {
        JSONObject jsonObject = new JSONObject();
        String oauthUserUrl = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=" + this.getToken() + "&userid=" + userId;
        System.out.println("获取成员的 客户列表信息url");
        System.out.println(oauthUserUrl);
        try {
            String message = HttpClient.get(oauthUserUrl);
            jsonObject = JSONObject.parseObject(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 获取客户明细
     *
     * @param clientId
     * @return
     */
    public JSONObject getClientDetail(String clientId) {
        JSONObject jsonObject = new JSONObject();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=" + this.getToken() + "&external_userid=" + clientId + "&cursor=CURSOR";
        System.out.println("获取成员的 客户列表信息url");
        System.out.println(url);
        try {
            String message = HttpClient.get(url);
            jsonObject = JSONObject.parseObject(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    public String getJsApiTicket() {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + this.getToken();
        String message = HttpClient.get(url);
        JSONObject tmpJson = JSONObject.parseObject(message);
        System.out.println("getJsApiTicketSJson:：" + tmpJson);
        return tmpJson.getString("ticket");
    }

    public String getJsAgentSignTicket() {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=" + this.getToken() + "&type=agent_config";
        String message = HttpClient.get(url);
        JSONObject tmpJson = JSONObject.parseObject(message);
        System.out.println("getJsAgentSignTicket:：" + tmpJson);
        return tmpJson.getString("ticket");
    }
}
